package com.ly.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.MsgDTO;
import com.ly.common.core.exception.ServiceException;
import com.ly.system.service.ISysCommonService;
import com.ly.test.handle.IMsgService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 通用服务-impl
 *
 * @author luoyun
 * @Date: 2025/6/09 21:45
 * @Note:
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysCommonServiceImpl implements ISysCommonService {

    private final List<IMsgService> msgServiceList;

    @Override
    public R sendMsg(MsgDTO dto) {
        String messageType = dto.getType();
        if (StrUtil.isEmpty(messageType)) {
            throw new ServiceException("消息类型未配置");
        }
        if (StrUtil.isEmpty(dto.getMsgContent()) && StrUtil.isEmpty(dto.getTemplateCode())) {
            throw new ServiceException("发送消息失败,消息内容为空！");
        }
        if (StrUtil.isEmpty(dto.getToUser())) {
            throw new ServiceException("接收人不能为空！");
        }
        String datas = dto.getParamsStr();
        if (StrUtil.isNotEmpty(datas)) {
            Map<String, Object> data = JSON.parseObject(datas, Map.class);
            dto.setParams(data);
        }
        msgServiceList.forEach(n -> {
            if (n.supports(messageType)) {
                n.sendMessage(dto);
            }
        });
        return R.ok(true, "消息发送成功！");
    }
}
